<template>
  <div class="manage">
    <el-dialog
      title="新增"
      :visible.sync="dialogVisible"
      width="50%"
      :before-close="handelClose">
      <!--新增表单信息 -->
      <el-form ref="form" :rules="rules" :inline="true" :model="form" label-width="80px">
        <el-form-item label="姓名" prop="username">
          <el-input placeholder="请输入姓名" v-model="form.username"></el-input>
        </el-form-item>
        <br/>
        <el-form-item label="头像" prop="avatar">
          <el-upload
            style="border:1px dashed #d1d1d1"
            class="avatar-uploader"
            :action="uploadURL"
            name="uploadFile"
            :show-file-list="false"
            :on-success="handleAvatarSuccess"
            :before-upload="beforeAvatarUpload">
            <img v-if="form.avatar" :src="form.avatar" class="avatar">
            <i v-else class="el-icon-plus avatar-uploader-icon"></i>
          </el-upload>
        </el-form-item>
        <br/>
        <el-form-item label="昵称" prop="nickname">
          <el-input placeholder="请输入昵称" v-model="form.nickname"></el-input>
        </el-form-item>
        <el-form-item label="密码" prop="password">
          <el-input placeholder="请输入密码" v-model="form.password"></el-input>
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input placeholder="请输入邮箱" v-model="form.email"></el-input>
        </el-form-item>
        <el-form-item label="联系方式" prop="phone">
          <el-input placeholder="请输入联系方式" v-model="form.phone"></el-input>
        </el-form-item>
        <el-form-item label="身份证号" prop="idNumber">
          <el-input placeholder="请输入身份证号" v-model="form.idNumber"></el-input>
        </el-form-item>
        <el-form-item label="房屋号" prop="houseId">
          <el-input placeholder="请输入房屋号" v-model="form.houseId"></el-input>
        </el-form-item>
        <el-form-item label="性别" prop="sex">
          <el-radio-group v-model="form.sex">
            <el-radio :label="1">男</el-radio>
            <el-radio :label="0">女</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="出生日期" prop="birth">
          <el-date-picker
            v-model="form.birth"
            type="date"
            placeholder="选择日期"
            value-format="yyyy-MM-dd">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="状态" prop="delFlag">
          <el-radio-group v-model="form.delFlag">
            <el-radio :label="0">正常</el-radio>
            <el-radio :label="1">停用</el-radio>
          </el-radio-group>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="cancel">取 消</el-button>
        <el-button type="primary" @click="submit">确 定</el-button>
      </span>
    </el-dialog>
    <!--文件上传-->
    <el-dialog
      title="导入"
      :visible.sync="fileShow"
      width="400px"
      :before-close="handleCloseFile">
      <el-upload
        class="upload-demo"
        drag
        ref="upload"
        :action="uploadURL"
        name="uploadFile"
        :data="{addOrUpdate}"
        :auto-upload="false"
        :before-upload="beforeUpload"
        :on-success="onSuccess">
        <i class="el-icon-upload"></i>
        <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
        <div class="el-upload__tip" slot="tip" style="text-align:center;">
          只能上传xls/xlsx文件，且不超过5MB。<el-link type="primary" style="font-size: 13px;" :href="userTemplate">下载模板</el-link>
          <br>
          <el-checkbox v-model="addOrUpdate"></el-checkbox>是否更新已经存在的用户数据
        </div>
      </el-upload>
      <span slot="footer" class="dialog-footer">
        <el-button @click="handleCloseFile">取 消</el-button>
        <el-button type="primary" @click="handleSubmitFile">确 定</el-button>
      </span>
    </el-dialog>
    <!--文件导出-->
    <el-dialog
      title="导出"
      :visible.sync="exportUsersFlag"
      width="20%"
      :before-close="bcexportUsersFlag">
      <div style="text-align: center;"><el-link type="primary" :href="exportUsers">点击下载</el-link></div>
      <span slot="footer" class="dialog-footer">
          <el-button @click="exportUsersFlag = false">取 消</el-button>
          <el-button type="primary" @click="exportUsersFlag = false">确 定</el-button>
        </span>
    </el-dialog>
    <!--form 搜索区-->
    <el-form :inline="true" :model="userForm">
      <el-form-item label="姓名">
        <el-input placeholder="请输入姓名" v-model="userForm.username" size="mini"></el-input>
      </el-form-item>
      <el-form-item label="邮箱">
        <el-input placeholder="请输入邮箱" v-model="userForm.email" size="mini"></el-input>
      </el-form-item>
      <el-form-item label="电话号">
        <el-input placeholder="请输入电话号" v-model="userForm.phone" size="mini"></el-input>
      </el-form-item>
      <el-form-item label="身份证号">
        <el-input placeholder="请输入身份证号" v-model="userForm.idNumber" size="mini"></el-input>
      </el-form-item>
      <el-form-item label="房屋号">
        <el-input placeholder="请输入房屋号" v-model="userForm.houseId" size="mini"></el-input>
      </el-form-item>
      <el-form-item label="状态">
        <el-select v-model="userForm.delFlag" clearable placeholder="状态" size="mini">
          <el-option
            v-for="item in delFlag"
            :key="item.code"
            :label="item.value"
            :value="item.code">
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="onSubmit" size="mini" plain><i class="el-icon-search"></i>搜 索</el-button>
        <el-button  @click="onReset" size="mini" plain><i class="el-icon-refresh"></i>重 置</el-button>
      </el-form-item>
    </el-form>
    <!--操作区-->
    <div class="manage-header">
      <el-button @click="handelAdd" type="primary" plain size="mini">
        <i class="el-icon-plus"></i>新增
      </el-button>
      <el-button @click="handelDelUsers" type="danger" plain size="mini" :disabled="disabled">
        <i class="el-icon-delete"></i>删除
      </el-button>
      <el-button @click="importUsers" type="info" plain size="mini">
        <i class="el-icon-upload2"></i>导入
      </el-button>
      <el-button @click="downloadUsers" type="warning" plain size="mini">
        <i class="el-icon-download"></i>导出
      </el-button>
    </div>
    <div class="common-table">
      <!--内容-->
      <el-table
        height="90%"
        :data="tableData"
        style="width: 100%"
        stripe
        @selection-change="handleSelectionChange">
        <el-table-column
        type="selection"
        width="55">
      </el-table-column>
        <el-table-column
          prop="username"
          label="姓名"
          fixed>
        </el-table-column>
        <el-table-column prop="" label="头像" fixed>
          <template slot-scope="scope">
            <el-avatar shape="square" v-if="scope.row.avatar" :src="scope.row.avatar">
              <img shape="square" src="../assets/fallback.png"/>
            </el-avatar>
          </template>
        </el-table-column>
        <el-table-column
          prop="nickname"
          label="昵称"
          fixed>
        </el-table-column>
        <el-table-column
          prop="password"
          label="密码">
        </el-table-column>
        <el-table-column
          prop="sex"
          label="性别">
          <template slot-scope="scope">
            <span>{{ scope.row.sex == 1 ? "男" : "女" }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="" label="出生日期" width="130">
          <template slot-scope="scope">
            {{ new Date(scope.row.birth).toLocaleDateString() }}
          </template>
        </el-table-column>
        <el-table-column
          prop="email"
          label="邮箱"
          width="180">
        </el-table-column>
        <el-table-column
          prop="phone"
          label="电话"
          width="160">
        </el-table-column>
        <el-table-column
          prop="idNumber"
          label="身份证号"
          width="170">
        </el-table-column>
        <el-table-column prop="" label="状态">
          <template slot-scope="scope">
            <a @click="updateDelFlag(scope.row)">
              <el-switch
                v-model="scope.row.delFlag==0 ? true : false"
                active-color="#13ce66"
                inactive-color="#ff4949">
              </el-switch>
            </a>
          </template>
        </el-table-column>
        <el-table-column
          prop="houseId"
          label="房屋号">
        </el-table-column>
        <el-table-column
          prop="createTime"
          width="170"
          sortable
          label="创建时间">
        </el-table-column>
        <el-table-column prop="" label="操作" width="150" fixed="right">
          <template slot-scope="scope">
            <el-button type="text" size="mini" @click="handelEditUser(scope.row)"><i class="el-icon-edit"></i>修改</el-button>
            <el-button type="text" size="mini" @click="handelDelUser(scope.row)"><i class="el-icon-delete"></i>删除</el-button>
          </template>
        </el-table-column>
      </el-table>
      <div class="pager">
        <el-pagination
          layout="prev, pager, next"
          :total="this.total"
          @current-change="handelPage">
        </el-pagination>
      </div>
    </div>
  </div>
</template>
<script>
    import { listQueryUser, saveOrUpdateUser, editUser, delUser, delUsers, downloadUsers } from "../api"
    export default {
        name: "User",
        data(){
            return{
                dialogVisible:false,
                form: {
                    id:null,
                    username: '',
                    avatar: '',
                    nickname: '',
                    password: '',
                    sex: 1,
                    email: '',
                    phone: '',
                    idNumber: '',
                    birth: '',
                    houseId: '',
                    delFlag: 0,
                },
                rules:{
                    username: [
                        {required: true,message: '请输入姓名'}
                    ],
                    password: [
                        {required: true,message: '请输入密码'}
                    ],
                    email: [
                        {required: true,message: '请输入邮箱'}
                    ],
                    phone: [
                        {required: true,message: '请输入手机号'}
                    ],
                    idNumber: [
                        {required: true,message: '请输入身份证号'}
                    ]
                },
                tableData: [],
                modelType: 0,  //0：新增，1：修改
                total: 0,
                pageData:{
                    page: 1,
                    limit: 10
                },
                delFlag: [
                    {
                        code: 0,
                        value: '正常'
                    },
                    {
                        code: 1,
                        value: '停用'
                    }
                ],
                userForm: {
                    username: "",
                    email: "",
                    phone: "",
                    idNumber: "",
                    houseId: "",
                    delFlag: null
                },
                userIds: [],
                disabled: true,
                fileShow: false,
                uploadURL: 'http://localhost:8080/user/importFileAddUsers',
                userTemplate: 'http://localhost:8080/cell_system/data/user/downloadTemplate/userTemplate.xlsx',
                exportUsers: '',
                addOrUpdate:false,
                exportUsersFlag: false,
                uploadURL: 'http://localhost:8080/user/uploadAvatar'
            }
        },
        methods:{
            //文件上传成功
            handleAvatarSuccess(res, file) {
                this.form.avatar=file.response
                //this.imageUrl = URL.createObjectURL(file.raw);
            },
            //文件上传之前
            beforeAvatarUpload(file) {
                const isJPG = file.type === 'image/jpeg';
                const isPNG = file.type === 'image/png';
                const isLt3M = file.size / 1024 / 1024 < 3;
                if (!isJPG && !isPNG) {
                    this.$message.error('上传头像图片只能是 JPG 或 PNG 格式!');
                    return false;
                }
                if (!isLt3M) {
                    this.$message.error('上传头像图片大小不能超过 3MB!');
                    return false;
                }
                return true;
            },
            //导入文件弹窗关闭
            handleCloseFile(){
                this.fileShow=false;
            },
            //导出文件弹窗关闭
            bcexportUsersFlag(){
                this.exportUsersFlag=false;
            },
            //文件提交
            handleSubmitFile(){
                this.$refs.upload.submit();
            },
            //文件上传之前
            beforeUpload(file){
                let accpeFileType=['xls','xlsx'];
                let type = file.name.split(".").slice(-1)[0].toLowerCase()
                const isLt5M = file.size / 1024 / 1024 < 5;
                if (accpeFileType.filter(item=> item==type).length==0){
                    this.$message.error('文件必须是.xls或.xlsx的文件!');
                    return false;
                }
                if (!isLt5M){
                    this.$message.error('上传文件大小不能超过 5MB!');
                    return false;
                }
                return true;
            },
            //文件上传成功
            onSuccess(response, file, fileList){
                this.listQueryUser();
                this.$message({
                    type: file.response.type,
                    message: (file.response.type=="error") ? ("更新失败！可能是用户名重名所导致") : ("导入"+file.name+","+file.response.message)
                });
            },
            //提交用户表单
            submit(){
                //进行校验
                this.$refs.form.validate((valid)=>{
                    if (valid){
                        const { roles, ...newRow } = this.form;
                        if (this.modelType == 0){
                            //新增
                            this.form.id=null;
                            saveOrUpdateUser(this.form).then(({ data })=>{
                                this.listQueryUser();
                                this.$message({
                                    type: data.type,
                                    message: data.message
                                });
                            });
                        }else{
                            //修改
                            saveOrUpdateUser(newRow).then(({ data }) => {
                                this.listQueryUser();
                                this.$message({
                                    type: data.type,
                                    message: data.message
                                });
                            });
                        }
                        this.handelClose();
                    }
                });
            },
            //弹窗关闭的时候
            handelClose(){
                //重置表单
                this.$refs.form.resetFields();
                this.dialogVisible=false;
            },
            //点击取消
            cancel(){
                this.handelClose();
            },
            //编辑
            handelEditUser(row){
                this.modelType=1;
                this.dialogVisible=true;
                //需要对当前的数据进行深拷贝，否则会出错，不能直接this.form=row;
                this.form=JSON.parse(JSON.stringify(row));
            },
            //删除
            handelDelUser(row){
                this.$confirm('此操作将永久删除该业主, 是否继续?', '提示', {
                    confirmButtonText: '确定',
                    cancelButtonText: '取消',
                    type: 'warning'
                }).then(() => {
                    delUser(row).then(({ data })=>{
                        this.listQueryUser();
                        this.$message({
                            type: data.type,
                            message: data.message
                        });
                    });
                }).catch(() => {
                    this.$message({
                        type: 'info',
                        message: '已取消删除'
                    });
                });
            },
            //修改状态
            updateDelFlag(row){
                this.$confirm('确定要“'+(row.delFlag == 0 ? "停用" : "启用")+'”“'+row.username+'吗？', '提示', {
                    confirmButtonText: '确定',
                    cancelButtonText: '取消',
                    type: 'warning'
                }).then(() => {
                    row.delFlag=(row.delFlag == 0 ? 1 : 0);
                    const { roles, ...newRow } = row;
                    //修改
                    saveOrUpdateUser(newRow).then(({ data }) => {
                        this.listQueryUser();
                        this.$message({
                            type: data.type,
                            message: data.message
                        });
                    });
                }).catch(() => {
                    this.$message({
                        type: 'info',
                        message: '已取消'
                    });
                });
            },
            //新增
            handelAdd(){
                this.form={
                    id:null,
                    username: '',
                    avatar: '',
                    nickname: '',
                    password: '',
                    sex: 1,
                    email: '',
                    phone: '',
                    idNumber: '',
                    birth: '',
                    houseId: '',
                    delFlag: 0,
                }
                this.modelType=0;
                this.dialogVisible=true;
            },
            //批量删除
            handelDelUsers(){
                this.$confirm('此操作将永久删除该业主, 是否继续?', '提示', {
                    confirmButtonText: '确定',
                    cancelButtonText: '取消',
                    type: 'warning'
                }).then(() => {
                    delUsers({userIds:this.userIds}).then(({ data })=>{
                        this.listQueryUser();
                        this.$message({
                            type: data.type,
                            message: data.message
                        });
                    });
                }).catch(() => {
                    this.$message({
                        type: 'info',
                        message: '已取消删除'
                    });
                });
            },
            //导入
            importUsers(){
                this.fileShow=true;
            },
            //导出
            downloadUsers(){
                this.exportUsersFlag=true;
                downloadUsers().then(({ data })=>{
                    this.exportUsers=data.data;
                });

            },
            //选中的记录
            handleSelectionChange(val){
                this.userIds=[];
                val.forEach(item=>{
                    this.userIds.push(item.id);
                });
                if (this.userIds.length>0){
                    this.disabled=false;
                }else{
                    this.disabled=true;
                }
            },
            //获取列表
            listQueryUser(){
                listQueryUser({...this.userForm,...this.pageData}).then(( {data} )=>{
                    //console.log(data)
                    this.tableData=data.list;
                    //如果data.count不存在 就为0
                    this.total=data.count || 0;
                });
            },
            //获取页码
            handelPage(val){
                this.pageData.page=val;
                this.listQueryUser();
            },
            //条件查询
            onSubmit(){
                this.listQueryUser();
            },
            //重置
            onReset(){
                this.userForm={
                    username: "",
                    email: "",
                    phone: "",
                    idNumber: "",
                    houseId: "",
                    delFlag: null
                }
            }
        },
        //页面首次加载时调用的地方
        mounted() {
            this.listQueryUser();
        }
    }
</script>

<style lang="less" scoped>
.manage{
  height: 90%;
  .manage-header{
    display: flex;
    //justify-content: space-between;
    align-items: center;
  }
  .common-table{
    position: relative;
    //动态计算高度
    height: calc(100% - 62px);
    .pager{
      position: absolute;
      bottom: 0;
      right: 20px;
    }
  }
}

.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}
.avatar-uploader .el-upload:hover {
  border-color: #409EFF;
}
.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  line-height: 178px;
  text-align: center;
}
.avatar {
  width: 178px;
  height: 178px;
  display: block;
}
</style>
